<?php
namespace app\common\model;

use think\Model;
use think\Db;

abstract class BaseMember extends Model
{
    //缓存配置
    protected $cache_options =  [
        'type'=>'memcached',
        'host'=>'127.0.0.1',
        'port'=>'11211',
        'prefix'=>'water',
        'expire'=>60
    ];
    /**
     * 会员详细信息
     * @param array $condition
     * @param string $field
     * @return array
     */
    abstract public function getMemberInfo($condition, $field );

    /**
     * 会员列表
     * @param array $condition
     * @param string $field
     * @param number $page
     * @param string $order
     */
    abstract public function getMemberList($condition , $field , $order , $page ,$pagesize);

    /**
     * 会员数量
     * @param array $condition
     * @return int
     */
    public function getMemberCount($condition){
        return Db::name('shop_member')->where($condition)->count();
    }

    /**
     * 登录时创建会话SESSION
     *
     * @param array $member_info 会员信息
     */
    public function createSession($member_info = array()) {
        if (empty($member_info) || !is_array($member_info)) return ;
        session('member_id',$member_info['member_id']);
        session('member_name',$member_info['member_name']);
        session('member_email',$member_info['member_email']);
        session('is_buy',$member_info['is_buy']);
        session('avatar',$member_info['member_avatar']);
        session('member_store',$member_info['member_store']);
        if (trim($member_info['openid'])){
            session('openid',$member_info['openid']);
        }
        session('member_paypwd',$member_info['member_paypwd']);
        session('member_sex',$member_info['member_sex']);
        session('member_truename',$member_info['member_truename']);

        $update_info	= array(
            'member_login_num'=> ($member_info['member_login_num']+1),
            'member_login_time'=> time(),
            'member_old_login_time'=> $member_info['member_login_time'],
            'member_login_ip'=> getIp(),
            'member_old_login_ip'=> $member_info['member_login_ip']
        );
        return $this->updateMember($update_info,$member_info['member_id']);
    }

    /**
     * 注册
     */
    public function register($register_info) {

        // 会员添加
        $member_info	= array();
        $member_info['member_name']		= $register_info['nickname'];
        $member_info['member_sex']       = isset($register_info['sex'])?$register_info['sex']:1;
        $member_info['member_avatar']		= !empty($register_info['headimgurl'])?$register_info['headimgurl']:config('default_head');
        $member_info['member_store']		= $register_info['member_store'];
        if(isset($register_info['parent'])&&!empty($register_info['parent'])){
            //获取父级用户信息，设定左右值
            $condition = array(
                'member_id'=>$register_info['parent'],
                'member_store'=>$member_info['member_store']
            );
            $parent = Db::name('shop_member')->field('member_left,member_right,member_level')->where($condition)->find();
            if(!empty($parent)){
                $right_map['member_right']  = ['>=',$parent['member_right']];
                $left_map['member_left']  = ['>=',$parent['member_right']];
                Db::name('shop_member')->where($right_map)->setInc('member_right', 2);
                Db::name('shop_member')->where($left_map)->setInc('member_left', 2);
                $member_info['member_left']=$parent['member_right'];
                $member_info['member_right']=$parent['member_right']+1;
                $member_info['member_level'] = $parent['member_level']+1;
            }else{
                //为空，则将此用户放入商城层级
                $condition = array(
                    'member_left'=>1,
                    'member_store'=>$member_info['member_store']
                );
                $parent = Db::name('shop_member')->field('member_left,member_right,member_level')->where($condition)->find();
                if(!empty($parent)){
                    //腾出空间left>member_right =>left+2 rgh>member_right =>rgh+2
                    $right_map['member_right']  = ['>=',$parent['member_right']];
                    $left_map['member_left']  = ['>=',$parent['member_right']];
                    Db::name('shop_member')->where($right_map)->setInc('member_right', 2);
                    Db::name('shop_member')->where($left_map)->setInc('member_left', 2);
                    $member_info['member_left']=$parent['member_right'];
                    $member_info['member_right']=$parent['member_right']+1;
                    $member_info['member_level'] = $parent['member_level']+1;
                }else{
                    //为空，则将左右值设为0
                    $member_info['member_left']=1;
                    $member_info['member_right']=2;
                    $member_info['member_level'] = 1;
                }
            }
        }else{
            //为空，则将此用户放入商城层级
            $condition = array(
                'member_left'=>1,
                'member_store'=>$member_info['member_store']
            );
            $parent = Db::name('shop_member')->field('member_left,member_right,member_level')->where($condition)->find();
            if(!empty($parent)){
                $right_map['member_right']  = ['>=',$parent['member_right']];
                $left_map['member_left']  = ['>=',$parent['member_right']];
                Db::name('shop_member')->where($right_map)->setInc('member_right', 2);
                Db::name('shop_member')->where($left_map)->setInc('member_left', 2);
                $member_info['member_left']=$parent['member_right'];
                $member_info['member_right']=$parent['member_right']+1;
                $member_info['member_level'] = $parent['member_level']+1;

            }else{
                //为空，则将左右值设为0
                $member_info['member_areainfo']=1;
                $member_info['member_areainfo']=2;
                $member_info['member_level'] = 1;
            }
        }

        if($register_info['country']=='CN'){
            $register_info['country'] = '中国';
        }else{
            $register_info['country'] = '';
        }
        $area_info = Db::name('shop_area')->where('area_name','like','%'.$register_info['city'].'%')->find();
        if(!empty($area_info)){
            $member_info['member_areaid']		= 0;
            $member_info['member_cityid']		= $area_info['area_id'];
            $member_info['member_provinceid']	= $area_info['area_parent_id'];
        }else{
            $member_info['member_areaid']		= 0;
            $member_info['member_cityid']		= 0;
            $member_info['member_provinceid']	= 0;
        }
        $member_info['member_areainfo'] = $register_info['country'].$register_info['province'].$register_info['city'];
        if(isset($register_info['openid'])&&!empty($register_info['openid'])){
            $member_info['openid']		=  $register_info['openid'];
        }
        $res =  $this->addMember($member_info);
        if($res){
            session('member_id',$res);
            session('member_name',$member_info['member_name']);
            session('member_email',$member_info['member_email']);
            session('is_buy',1);
            session('avatar',$member_info['member_avatar']);
            session('member_store',$member_info['member_store']);
            if (trim($member_info['openid'])){
                session('openid',$member_info['openid']);
            }
            session('member_paypwd',$member_info['member_paypwd']);
            session('member_sex',$member_info['member_sex']);
            session('member_truename',$member_info['member_truename']);
        }else{
            return $res;
        }
    }
    /**
     * 注册商城会员
     *
     * @param	array $param 会员信息
     * @return	array 数组格式的返回结果
     */
    public function addMember($param) {
        if(empty($param)) {
            return false;
        }
        $member_info	= array();
        $member_info['member_name']			= $param['member_name'];
        $member_info['member_mobile']		= isset($param['member_mobile'])?$param['member_mobile']:'';
        $member_info['member_time']			= time();
        $member_info['member_login_time'] 	= $member_info['member_time'];
        $member_info['member_old_login_time'] = $member_info['member_time'];
        $member_info['member_login_ip']		= getIp();
        $member_info['member_old_login_ip']	= $member_info['member_login_ip'];

        $member_info['member_sex']			= isset($param['member_sex'])?$param['member_sex']:1;
        $member_info['member_avatar']		= $param['member_avatar'];

        $member_info['member_areaid']		= isset($param['member_areaid'])?intval($param['member_areaid']):0;
        $member_info['member_cityid']		= isset($param['member_cityid'])?intval($param['member_cityid']):0;
        $member_info['member_provinceid']		= isset($param['member_provinceid'])?intval($param['member_provinceid']):0;
        $member_info['member_areainfo']		= isset($param['member_areainfo'])?$param['member_areainfo']:'';
        $member_info['member_left']		= isset($param['member_left'])?intval($param['member_left']):0;
        $member_info['member_right']		= isset($param['member_right'])?intval($param['member_right']):0;
        $member_info['member_level']		= isset($param['member_level'])?intval($param['member_level']):0;
        $member_info['member_store']		= isset($param['member_store'])?intval($param['member_store']):0;

        if(isset($param['member_truename'])&&!empty($param['member_truename'])){
            $member_info['member_truename']		= $param['member_truename'];
        }
        if(isset($param['openid'])&&!empty($param['openid'])){
            $member_info['openid']		=  $param['openid'];
        }
        $result = Db::name('shop_member')->insertGetId($member_info);
        if($result) {
            return $result;
        } else {
            return false;
        }
    }

    /**
     * 更新会员信息
     *
     * @param	array $param 更改信息
     * @param	int $member_id 会员条件 id
     * @return	array 数组格式的返回结果
     */
    public function updateMember($param,$member_id) {
        if(empty($param)) {
            return false;
        }
        //得到条件语句
        if(is_array($member_id)&&!empty($member_id)){
            cache($this->cache_options);
            cache(null,'member');
            return Db::name('shop_member')->where('member_id','in',$member_id)->where(array('member_store'=>session('shop')))->update($param);
        }else{
            $condition	= array(
                'member_id'=> intval($member_id)
            );
            cache($this->cache_options);
            cache(null,'member');
            return Db::name('shop_member')->where($condition)->where(array('member_store'=>session('shop')))->update($param);
        }
    }

    /**
     * 删除会员
     *
     * @param int $id 记录ID
     * @return array $rs_row 返回数组形式的查询结果
     */
    public function del($id){
        if(is_array($id)&&!empty($id)){
            $result = Db::name('shop_member')->where('member_id','in',$id)->where(array('member_store'=>session('shop')))->delete();
            return $result;
        }else{
            $id = intval($id);
            if ( $id > 0){
                $result = Db::name('shop_member')->where(array('member_store'=>session('shop')))->delete($id);
                return $result;
            }else {
                return false;
            }
        }

    }
    /*
     * 会员充值
     * 赵坤
     * 20161229
     * */
    public function recharge($member){
        // 启动事务
        Db::startTrans();
        try{
            //充值并记录账单
            $data = array();

            $data['shop'] = session('shop');
            $data['admin_name'] = session('seller_name')?session('seller_name'):'';


            $data['member_id'] = $member['member_id'];
            $data['member_name'] = $member['member_name'];
            $data['amount'] = $member['amount'];
            $data['pdr_sn'] = $member['pdr_sn'];
           $res = $this->changePd('recharge',$data);
            // 提交事务
            Db::commit();
            return $res;
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return false;
        }
    }
    /**
     * 变更预存款
     * @param unknown $change_type
     * @param unknown $data
     * @throws Exception
     * @return unknown
     */
    public function changePd($change_type,$data = array()) {
        $data_log = array();
        $data_pd = array();
        $data_log['lg_seller_id']=$data['shop'];

        $data_log['lg_member_id'] = $data['member_id'];
        $data_log['lg_member_name'] = $data['member_name'];
        $data_log['lg_add_time'] = time();
        $data_log['lg_type'] = $change_type;
        switch ($change_type){
            case 'order_pay':
                $data_log['lg_av_amount'] = -$data['amount'];
                $data_log['lg_desc'] = '下单，支付预存款，订单号: '.$data['order_sn'];
                $data_pd['available_predeposit'] = array('exp','available_predeposit-'.$data['amount']);
                break;
            case 'order_freeze':
                $data_log['lg_av_amount'] = -$data['amount'];
                $data_log['lg_freeze_amount'] = $data['amount'];
                $data_log['lg_desc'] = '下单，冻结预存款，订单号: '.$data['order_sn'];
                $data_pd['freeze_predeposit'] = array('exp','freeze_predeposit+'.$data['amount']);
                $data_pd['available_predeposit'] = array('exp','available_predeposit-'.$data['amount']);
                break;
            case 'order_cancel':
                $data_log['lg_av_amount'] = $data['amount'];
                $data_log['lg_freeze_amount'] = -$data['amount'];
                $data_log['lg_desc'] = '取消订单，解冻预存款，订单号: '.$data['order_sn'];
                $data_pd['freeze_predeposit'] = array('exp','freeze_predeposit-'.$data['amount']);
                $data_pd['available_predeposit'] = array('exp','available_predeposit+'.$data['amount']);
                break;
            case 'order_comb_pay':
                $data_log['lg_freeze_amount'] = -$data['amount'];
                $data_log['lg_desc'] = '下单，支付被冻结的预存款，订单号: '.$data['order_sn'];
                $data_pd['freeze_predeposit'] = array('exp','freeze_predeposit-'.$data['amount']);
                break;
            case 'recharge':
                $data_log['lg_av_amount'] = $data['amount'];
                $data_log['lg_desc'] = '充值，充值单号: '.$data['pdr_sn'];
                $data_log['lg_admin_name'] = $data['admin_name'];
                $data_pd['available_predeposit'] = array('exp','available_predeposit+'.$data['amount']);
                break;
            case 'refund':
                $data_log['lg_av_amount'] = $data['amount'];
                $data_log['lg_desc'] = '确认退款，订单号: '.$data['order_sn'];
                $data_pd['available_predeposit'] = array('exp','available_predeposit+'.$data['amount']);
                break;
            case 'cash_apply':
                $data_log['lg_av_amount'] = -$data['amount'];
                $data_log['lg_freeze_amount'] = $data['amount'];
                $data_log['lg_desc'] = '申请提现，冻结预存款，提现单号: '.$data['order_sn'];
                $data_pd['available_predeposit'] = array('exp','available_predeposit-'.$data['amount']);
                $data_pd['freeze_predeposit'] = array('exp','freeze_predeposit+'.$data['amount']);
                break;
            case 'cash_pay':
                $data_log['lg_freeze_amount'] = -$data['amount'];
                $data_log['lg_desc'] = '提现成功，提现单号: '.$data['order_sn'];
                $data_log['lg_admin_name'] = $data['admin_name'];
                $data_pd['freeze_predeposit'] = array('exp','freeze_predeposit-'.$data['amount']);
                break;
            case 'cash_del':
                $data_log['lg_av_amount'] = $data['amount'];
                $data_log['lg_freeze_amount'] = -$data['amount'];
                $data_log['lg_desc'] = '取消提现申请，解冻预存款，提现单号: '.$data['order_sn'];
                $data_log['lg_admin_name'] = $data['admin_name'];
                $data_pd['available_predeposit'] = array('exp','available_predeposit+'.$data['amount']);
                $data_pd['freeze_predeposit'] = array('exp','freeze_predeposit-'.$data['amount']);
                break;
            default:
                throw new \Exception('参数错误');
                break;
        }
        $update = Db::name('shop_member')->where(array('member_id'=>$data['member_id']))->update($data_pd);
        if (!$update) {
            throw new \Exception('更新用户信息失败');
        }
        $insert = Db::name('shop_pd_log')->insert($data_log);
        if (!$insert) {
            throw new \Exception('记录账单失败');
        }
        return $insert;
    }
}